package com.example.prom.ok.y2022.controller.kyc3.loqate;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;

import com.example.prom.ok.y2022.dto.loqate.*;
import com.example.prom.ok.y2022.enums.ResponseErrorCodeEnum;
import com.example.prom.utils.HttpClientSingleton;
import com.example.prom.utils.HttpNewUtils;
import com.example.prom.utils.ResponseResult;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.IOUtils;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.springframework.stereotype.Component;

import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Slf4j
@Component
public class KYCLoqateService {

    private static final String API_KEY = "ZK21-TE16-DC95-HR81";
    public ResponseResult captureFind(CaptureFindReqDTO captureFindReqDTO) {
        try {
            String requestUrl = "https://api.addressy.com/Capture/Interactive/Find/v1.1/json3.ws";

            HttpClient httpClient = HttpClientSingleton.getLongCustomHttpClient();

            Map<String, String> queryMap = new HashMap<>();
            queryMap.put("key", API_KEY);
            queryMap.put("Text", captureFindReqDTO.getText());
            queryMap.put("IsMiddleware", "true");
//            if(StringUtils.isNotEmpty(captureFindReqDTO.getCountries())) {
                queryMap.put("Countries", captureFindReqDTO.getCountries());
//            }
//            if (Objects.nonNull(captureFindReqDTO.getLimit())) {
                queryMap.put("Limit", captureFindReqDTO.getLimit().toString());
//            }
            queryMap.put("Language", captureFindReqDTO.getLanguage());
            HttpResponse httpResponse = HttpNewUtils.doPostByForm(requestUrl, null, httpClient, null, queryMap, null);
            String result = IOUtils.toString(httpResponse.getEntity().getContent(), StandardCharsets.UTF_8);
            log.info("KYCLoqateService captureFind result:{}", result);
            CaptureFindRespDTO captureFindRespDTO = new CaptureFindRespDTO();
            if (httpResponse.getStatusLine().getStatusCode() == 200) {
                JSONObject jsonObject = JSON.parseObject(result, JSONObject.class);
                String items = jsonObject.get("Items").toString();
                List<CaptureFindResultItem> resultItems = JSON.parseObject(items, List.class);
                captureFindRespDTO.setResults(resultItems);
                log.info("KYCLoqateService captureFind success result:{}", JSON.toJSONString(captureFindRespDTO));
                return ResponseResult.build(ResponseErrorCodeEnum.SUCCESS, captureFindRespDTO);
            } else {
                JSONObject jsonObject = JSON.parseObject(result, JSONObject.class);
                String items = jsonObject.get("Items").toString();
                List<ErrorItem> resultItems = JSON.parseObject(items, List.class);
                captureFindRespDTO.setErrors(resultItems);
                log.info("KYCLoqateService captureFind failed result:{}", JSON.toJSONString(captureFindRespDTO));
                return ResponseResult.build(ResponseErrorCodeEnum.THIRD_RETURN_ERROR, captureFindRespDTO);
            }

        } catch (Exception e) {
            log.error("KYCLoqateService captureFind exception", e);
            return ResponseResult.build(ResponseErrorCodeEnum.INTERNAL_OTHER_EXCEPTION, new CaptureFindRespDTO());
        }
    }
    public ResponseResult captureRetrieve(String id) {
        try {
            String requestUrl = "https://api.addressy.com/Capture/Interactive/Retrieve/v1.1/json3.ws";

            HttpClient httpClient = HttpClientSingleton.getLongCustomHttpClient();

            Map<String, String> queryMap = new HashMap<>();
            queryMap.put("key", API_KEY);
            queryMap.put("id", id);
            HttpResponse httpResponse = HttpNewUtils.doPostByForm(requestUrl, null, httpClient, null, queryMap, null);
            String result = IOUtils.toString(httpResponse.getEntity().getContent(), StandardCharsets.UTF_8);
            CaptureRetrieveRespDTO retrieveRespDTO = new CaptureRetrieveRespDTO();
            if (httpResponse.getStatusLine().getStatusCode() == 200) {
                JSONObject jsonObject = JSON.parseObject(result, JSONObject.class);
                String items = jsonObject.get("Items").toString();
                List<CaptureRetrieveResultItem> resultItems = JSON.parseObject(items, List.class);
                retrieveRespDTO.setResultItems(resultItems);
                log.info("KYCLoqateService captureRetrieve success result:{}", JSON.toJSONString(retrieveRespDTO));
                return ResponseResult.build(ResponseErrorCodeEnum.SUCCESS, retrieveRespDTO);
            } else {
                JSONObject jsonObject = JSON.parseObject(result, JSONObject.class);
                String items = jsonObject.get("Items").toString();
                List<ErrorItem> errorItems= JSON.parseObject(items, List.class);
                retrieveRespDTO.setErrors(errorItems);
                log.info("KYCLoqateService captureRetrieve failed result:{}", JSON.toJSONString(retrieveRespDTO));
                return ResponseResult.build(ResponseErrorCodeEnum.THIRD_RETURN_ERROR, retrieveRespDTO);
            }
        } catch (Exception e) {
            log.error("KYCLoqateService captureRetrieve exception", e);
            return ResponseResult.build(ResponseErrorCodeEnum.INTERNAL_OTHER_EXCEPTION, new CaptureFindRespDTO());
        }
    }

}